package com.yugao.fintech.antelope.base.config.core;

import com.yugao.fintech.antelope.base.config.model.ActionTypeEnum;
import com.yugao.fintech.antelope.base.model.enums.ConfigKeyEnum;
import com.yugao.fintech.antelope.base.model.module.tenant.TenantContextHolder;
import com.yugao.fintech.framework.assistant.utils.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.cloud.bus.event.Destination;
import org.springframework.cloud.bus.event.PathDestinationFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
public class DynamicConfigServiceImpl implements DynamicConfigService {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    private BusProperties busProperties;

    @Autowired
    private PathDestinationFactory pathDestinationFactory;

    public void publishRouteEvent(ConfigMsg configMsg) {
        Destination destination = pathDestinationFactory.getDestination("**");
        if (Objects.isNull(configMsg.getTenantId())) {
            configMsg.setTenantId(TenantContextHolder.get().getTenantId());
        }
        RemoteConfigEvent remoteConfigEvent = new RemoteConfigEvent(busProperties.getId(), busProperties.getId(), destination, configMsg.toMessage());
        try {
            applicationEventPublisher.publishEvent(remoteConfigEvent);
        } catch (Exception e) {
            log.error("bus publish event fail:", e);
            throw new BizException("同步配置失败");
        }
    }

    @Override
    public void publishDeleteConfigEvent(ConfigKeyEnum configKey) {
        if (Objects.isNull(configKey)) {
            return;
        }
        ConfigMsg payload = ConfigMsg.builder().tenantId(TenantContextHolder.get().getTenantId())
                .configKey(configKey.getKey()).actionType(ActionTypeEnum.DELETE).build();
        publishRouteEvent(payload);
    }

    @Override
    public void publishRefreshConfigEvent(ConfigMsg payload) {
        Long tenantId = ObjectUtils.defaultIfNull(payload.getTenantId(), TenantContextHolder.get().getTenantId());
        payload.setTenantId(tenantId);
        payload.setActionType(ActionTypeEnum.UPDATE_OR_SAVE);
        publishRouteEvent(payload);
    }
}